package com.asia5b.a5mall.middleware.widget;

import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

/**
 * Created by zhangyuncai on 2020/5/7.
 */
public abstract class OnViewPagerListener extends RecyclerView.OnScrollListener {
    boolean mScrolled = false;
    private final PagerSnapHelper pagerSnapHelper;

    protected OnViewPagerListener(PagerSnapHelper pagerSnapHelper) {
        this.pagerSnapHelper = pagerSnapHelper;
    }


    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (mScrolled) {
            try {
                View snapView = pagerSnapHelper.findSnapView(recyclerView.getLayoutManager());
                if (snapView == null) {
                    return;
                }
                if (recyclerView.getLayoutManager() == null) {
                    return;
                }
                int selectPostion = recyclerView.getLayoutManager().getPosition(snapView);
                onPageSelected(selectPostion, newState == RecyclerView.SCROLL_STATE_IDLE);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //todo 停止中获取到的当前页面position
                    mScrolled = false;
                } else {
                    //todo 滑动中获取到的当前页面position
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (dx != 0 || dy != 0) {
            mScrolled = true;
        }
    }

    /**
     * @param position 选中的页面
     * @param isIdle   页面是否滑动停止
     */
   public abstract void onPageSelected(int position, boolean isIdle);


}
